<template>
  <div class="article-list">
    <!-- 列表 -->
    <van-pull-refresh
      v-model="isRefreshLoading"
      @refresh="onRefresh"
      :success-duration="1500"
      :success-text="refreshSuceessText"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败,点击重新加载"
        @load="onLoad"
      >
        <!-- 文章列表项组件 -->
        <article-item
          v-for="(article, index) in list"
          :key="index"
          :article="article"
        ></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article.js'
// 导入文章列表组件
import ArticleItem from '@/components/article-item/index.vue'
export default {
  name: 'ArticleList',
  props: {
    channel: {
      type: Object,
      require: true
    }
  },
  components: {
    ArticleItem
  },
  data () {
    return {
      list: [], // 加载数据
      loading: false, // 加载状态
      finished: false, // 加载完成
      timestamp: Date.now(), // 时间戳
      error: false,
      isRefreshLoading: false,
      refreshSuceessText: ''
    }
  },
  created () {

  },
  methods: {
    async onLoad () {
      // 获取文章列表
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id, // 频道ID
          timestamp: this.timestamp, // 你可以把 timestamp 理解为页码
          with_top: 1 // 如果请求第1页数据：当前最新时间戳 Date.now
        })
        const { results } = data.data
        this.list.push(...results)
        this.loading = false
        // this.finished = true // todo,终止发请求
        if (results.length === 0) {
          this.finished = true
        } else {
          this.timestamp = data.data.pre_timestamp
        }
      } catch (e) {
        console.error(e)
      }
    },
    // 下拉刷新
    async onRefresh () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id, // 频道ID
          timestamp: Date.now(), // 你可以把 timestamp 理解为页码
          with_top: 1 // 如果请求第1页数据：当前最新时间戳 Date.now
        })
        const { results } = data.data
        this.list.unshift(...results)
        // 关闭下拉刷新的loading 状态
        this.isRefreshLoading = false
        // 更新下拉刷新文本的成功提示
        this.refreshSuceessText = `刷新成功，更新了${results.length}条数据`
      } catch (e) {
        this.isRefreshLoading = false
        this.refreshSuceessText = '请稍后再试'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>
